package com.kehutong.tag.service;

import com.kehutong.common.errcode.Result;
import com.kehutong.crm.entity.Tag;
import com.kehutong.crm.enums.TagSourceType;
import com.kehutong.tag.dao.UserTagDao;
import com.kehutong.tag.entity.CustomizeTag;
import com.kehutong.tag.entity.UserTag;
import org.coraframework.bean.Beans;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.jdbc.execute.PageCondition;
import org.coraframework.orm.jdbc.execute.QueryCondition;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.EnumUtil;
import org.coraframework.util.Objects;
import org.coraframework.util.UUIDGenerator;

import java.io.IOException;
import java.util.*;

/**
 * 用户标签服务类
 * @author: liukunlong
 * @date: 2021-08-09 10:26
 */
@WebService("/crm/user/tag/service")
public class UserTagService {

    static final Logger logger = LoggerFactory.getLogger(UserTagService.class);

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private UserTagDao userTagDao;

    /**
     * 标签使用用户分页列表
     *
     * @param jsonObject 查询对象
     * @return 标签使用用户分页列表
     * @throws IOException 操作异常
     */
    @ReqMapping("/list")
    public List<UserTag> list(JSONObject jsonObject) throws Exception {
        List<UserTag> result = null;
        result = jdbcSession.findArray(UserTag.class)
                .eq(jsonObject, "tagNo", "communityNo","type","tagName")
                .like(jsonObject, "tagGroupName","userName")
                .eq("deleted", false)
                .order("createTime", "desc").exe();
        return result;
    }

    /**
     * 标签使用用户分页列表
     *
     * @param jsonObject 查询对象
     * @return 标签使用用户分页列表
     * @throws IOException 操作异常
     */
    @ReqMapping("/page")
    public Page<UserTag> page(JSONObject jsonObject) throws Exception {
        //标签编号
        String tagNo=jsonObject.getString("tagNo");
        Page<UserTag> result = null;
        FindPage<UserTag> findPage = jdbcSession.findPage(UserTag.class)
                .eq(jsonObject, "tagNo", "communityNo","type")
                .like(jsonObject, "tagGroupName","tagName","userName")
                .eq("deleted", false)
                .order("createTime", "desc")
                .page(jsonObject);
        result = findPage.exe();
        return result;
    }


    @ReqMapping("/count")
    public Map<String,Object> getUseTagCount(JSONObject jsonObject){
        QueryCondition query = Condition.createQuery(false);
        query.eq("deleted", false);
        query.order("createTime","desc");
        query.eq(jsonObject,"tagNo");
        return userTagDao.getUserTagCount(query);
    }


    @ReqMapping("/user/tag/group/list")
    public List<Map<String,Object>> getUserTagGroupList(JSONObject jsonObject){
        QueryCondition query = Condition.createQuery(false);
        query.in(jsonObject,"type");
            query.eq(jsonObject,"userNo");
        query.eq("deleted", false);
        query.order("createTime","desc");
        return userTagDao.getUserTagGroupList(query);
    }

    @ReqMapping("/user/tag/list")
    public List<Map<String,Object>> getUserTagList(JSONObject jsonObject){
        QueryCondition query = Condition.createQuery(false);
        query.in(jsonObject,"type");
        query.eq(jsonObject,"tagGroupName","userNo");
        query.eq("deleted", false);
        query.order("createTime","desc");
        JSONArray userNos=jsonObject.getJSONArray("userNos");
        if(Objects.nonEmpty(userNos)){
            query.in("userNo",userNos);
        }
        return userTagDao.getUserTagList(query);
    }

    /**
     * 批量打业务相关的用户标签
     *
     * 1已存在进行更新操作
     * 2.不存在进行新增操作
     * @param jsonObject 查询对象
     * @return
     * @throws Exception
     */
    @ReqMapping("/batch/add")
    public Object batchAdd(JSONObject jsonObject) throws Exception {
        String typeVal = jsonObject.getString("type");
        TagSourceType type=EnumUtil.getEnum(TagSourceType.class, typeVal);
        String userNo = jsonObject.getString("userNo");
        String userName = jsonObject.getString("userName");
        String communityNo = jsonObject.getString("communityNo");
        String communityName = jsonObject.getString("communityName");
        String createBy = jsonObject.getString("createBy");
        String createName = jsonObject.getString("createName");
        JSONArray userTagListJsonArray = jsonObject.getJSONArray("userTagList");
        if (Objects.nonEmpty(userTagListJsonArray)) {
            JSONObject condition = new JSONObject();
            condition.put("userNo", userNo);
            condition.put("createBy",createBy);
            condition.put("communityNo", communityNo);
            //标签与标记员工编号映射
            Map<String, UserTag> tagMapping = new HashMap<>();
            List<UserTag> dbUserTagList = jdbcSession.findArray(UserTag.class)
                    .eq(condition, "userNo", "createBy", "communityNo").exe();
            dbUserTagList.forEach(v -> {
                tagMapping.put(v.getTagNo(),v);
            });
            List<UserTag> addUserTagList = new ArrayList<>();
            List<UserTag> updateUserTagList = new ArrayList<>();
            for (Object tagObj : userTagListJsonArray) {
                JSONObject tag = (JSONObject) tagObj;
                String tagNo=tag.getString("id");
                if(!tagMapping.containsKey(tagNo)){
                    UserTag userTag = Pool.newInstance(UserTag.class, UUIDGenerator.randomUUID());
                    Beans.from(tag).to(userTag).exclude("id").igornNull().copy();
                    userTag.setUserNo(userNo);
                    userTag.setUserName(userName);
                    userTag.setType(type);
                    userTag.setTagGroupNo(tag.getString("pid"));
                    userTag.setTagGroupName(tag.getString("pname"));
                    userTag.setTagNo(tag.getString("id"));
                    userTag.setTagName(tag.getString("name"));
                    userTag.setCommunityNo(communityNo);
                    userTag.setCommunityName(communityName);
                    userTag.setCreateBy(createBy);
                    userTag.setCreateName(createName);
                    addUserTagList.add(userTag);
                }else{
                    UserTag userTag=tagMapping.get(tagNo);
                    userTag.setTagGroupName(tag.getString("pname"));
                    userTag.setTagName(tag.getString("name"));
                    userTag.setUserName(userName);
                    updateUserTagList.add(userTag);
                }
            }
            if(Objects.nonEmpty(addUserTagList)){
                jdbcSession.insert(addUserTagList);
            }
            if(Objects.nonEmpty(updateUserTagList)){
                jdbcSession.updateById(updateUserTagList);
            }
        }
        return Result.success();
    }

    /**
     * 批量打第三方相关的用户标签
     * 1.首先删除企业微信打的标签
     * 2.新增相关标签
     * @param jsonObject 查询对象
     * @return
     * @throws Exception
     */
    @ReqMapping("/third/batch/add")
    public Object thirdBatchAdd(JSONObject jsonObject) throws Exception {
        String userNo = jsonObject.getString("userNo");
        String userName = jsonObject.getString("userName");
        String communityNo = jsonObject.getString("communityNo");
        String communityName = jsonObject.getString("communityName");
        String createBy = jsonObject.getString("createBy");
        String createName = jsonObject.getString("createName");
        JSONArray tagIdArray = jsonObject.getJSONArray("tagIds");
        if (Objects.nonEmpty(tagIdArray)) {
            JSONObject condition = new JSONObject();
            condition.put("userNo", userNo);
            condition.put("createBy",createBy);
            condition.put("communityNo", communityNo);
            condition.put("type",TagSourceType.THIRD_PARTY_TAG.getId());
            List<UserTag> dbUserTagList = jdbcSession.findArray(UserTag.class)
                    .eq(condition, "userNo", "createBy", "communityNo","type").exe();
            jdbcSession.deleteById(dbUserTagList);
            List<UserTag> addUserTagList = new ArrayList<>();
            Set<String> mapping=new HashSet<>();
            for (Object tagId : tagIdArray) {
                String tagNo=(String)tagId;
                Tag dbTag=jdbcSession.findById(Tag.class,tagNo);
                Tag dbGroupTag=jdbcSession.findById(Tag.class,dbTag.getPid());
                UserTag userTag = Pool.newInstance(UserTag.class, UUIDGenerator.randomUUID());
                userTag.setUserNo(userNo);
                userTag.setUserName(userName);
                userTag.setType(TagSourceType.THIRD_PARTY_TAG);
                userTag.setTagGroupNo(dbGroupTag.getId());
                userTag.setTagGroupName(dbGroupTag.getName());
                userTag.setTagNo(dbTag.getId());
                userTag.setTagName(dbTag.getName());
                userTag.setCommunityNo(communityNo);
                userTag.setCommunityName(communityName);
                userTag.setCreateBy(createBy);
                userTag.setCreateName(createName);
                //去除微信同步重复标签问题
                String key=userNo+""+dbTag.getId();
                if(!mapping.contains(key)){
                    addUserTagList.add(userTag);
                    mapping.add(userNo+""+dbTag.getId());
                }

            }
            if(Objects.nonEmpty(addUserTagList)){
                jdbcSession.insert(addUserTagList);
            }
        }
        return Result.success();
    }

}
